/*
 * @Description: APW自动复制脚本
 * @Date: 2020-09-22 19:48:57
 * @creator: tangxiaobin
 */
init();
const CLASS_NAMES = ["knife4j-api-summary-path", "knife4j-api-title"];

function init() {
  window.addEventListener("click", handleClick); // 全局点击复制对应dom
}

function handleClick(e) {
  let url = "";
  const targetClassName = e.target.getAttribute("class");

  if (isWantDom(e)) {
    url = e.target.innerText;
  }

  if (targetClassName === "knife4j-api-summary") {
    url = parseRequestTemplate(e);
  }

  if (url) copyToClipboard(url);
}

function isWantDom(e) {
  let classStr = e.target.getAttribute("class"); // URL
  if (!classStr) classStr = e.target.parentNode.parentNode.getAttribute("class"); // 标题
  if (!classStr) return;

  classStr = classStr.split(" ")[0];
  if (CLASS_NAMES.includes(classStr)) return true;

  if (e.target.tagName === "TD") return true;

  console.log("T - file: content-script.js - line 24 - classStr", classStr);
  return false;
}

function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var result = window.location.search.substr(1).match(reg);
  if (result !== null) {
    return unescape(result[2]);
  }
  return null;
}

function copyToClipboard(str) {
  // 创建元素用于复制
  var aux = document.createElement("textarea");
  // 设置元素内容
  aux.value = str;

  // 将元素插入页面进行调用
  document.body.appendChild(aux);

  // 复制内容
  aux.select();

  // 将内容复制到剪贴板
  document.execCommand("copy");

  // 删除创建元素
  document.body.removeChild(aux);

  //提示
  showMessage(aux.value, "success");
}

function showMessage(message, type, time = 1000) {
  var aux = document.createElement("div");

  let str = "";
  switch (type) {
    case "success":
      str =
        '<div class="success-message" style="text-align: center;background-color:#67C23A;;color: #ffffff;position: fixed;left: 43%;top: 10%;line-height: 40px;padding:8px;border-radius: 5px;z-index: 9999">\n' +
        message +
        "</div>";
      break;
    case "error":
      str =
        '<div class="error-message" style="width: 300px;height: 40px;text-align: center;background-color: #f5f0e5;color: rgba(238,99,99,0.8);position: fixed;left: 43%;top: 10%;line-height: 40px;border-radius: 5px;;z-index: 9999">\n' +
        '    <span class="mes-text">' +
        message +
        "</span></div>";
  }

  aux.innerHTML = str;
  document.body.appendChild(aux);

  setTimeout(function () {
    console.log('Tang: showMessage -> document.getElementsByClassName(type + "-message")', aux);
    document.body.removeChild(aux);
  }, time);
}

function parseRequestTemplate(e) {
  const currentDom = $(e.target).parents(".document").eq(0);

  currentDom.find(".knife4j-api-summary-method").text();

  console.log("T - file: content-script.js - line 104 - parent", parent);

  const method = currentDom.find(".knife4j-api-summary-method").text().toLowerCase().trim();
  console.log('TT > method', method)

  const url = currentDom.find(".knife4j-api-summary-path").text();
  // console.log('TT > fullUrl', fullUrl)
  // const prefixLen = fullUrl.split("/")[0].length;
  // const url = fullUrl;

  const fnName = url.split("/").slice(-1)[0];
  const describe = currentDom.find(".knife4j-api-title span").text();

  const paramsArr = [];

  currentDom
    .find(".ant-table-body")
    .eq(0)
    .find("tr")
    .each(function (i) {
      console.log("T - file: content-script.js - line 103 - i", i);
      if (i !== 0) {
        var key = $(this).find("td:eq(0)").text();
        var name = $(this).find("td:eq(1)").text();
        paramsArr.push(`${key}:${name}`);
      }
    });

  const bodyKeyName = method.trim() === "get" ? "params" : "data";

  const paramsStr = paramsArr.length > 0 ? `@param {Object} ${bodyKeyName} {${paramsArr.join(", ")}}` : "";

  const result = `
/** 
* ${describe}
* ${paramsStr}
* @returns
*/
export const ${fnName} = (${paramsStr ? bodyKeyName : ""}) => request ({
    url:'${url}',
    method:'${method}', ${paramsStr ? bodyKeyName : ""} 
})
`;
  console.log("T - file: content-script.js - line 129 - result", result);
  return result;
}
